此範例展示了如何結合使用 Rest Parameters 和 Spread Operator:
...titles):將多餘的參數收集到一個陣列中...person):將陣列元素展開作為函數參數function showPerson(firstname, lastname, ...titles) {
let sentence = firstname + " " + lastname + " is ";
for (let i = 0; i < titles.length; i++) {
if (i !== titles.length - 1) {
sentence += "a " + titles[i] + ", ";
} else {
if (titles.length === 1) {
sentence += "a " + titles[i];
} else {
sentence += "and a " + titles[i];
}
}
}
console.log(sentence);
}
// ✅ 改成使用 Spread 呼叫
const person1 = ["Keith", "Fung", "Firefighter"];
const person2 = ["Marvin", "Chan", "Highschool student", "Pet Owner"];
const person3 = ["Justin", "Lau", "Consultant", "Hiker", "Camper"];
const person4 = ["Justin", "Lau", "Consultant", "Hiker", "Camper", "Blogger", "Foodie"];
showPerson(...person1);
showPerson(...person2);
showPerson(...person3);
showPerson(...person4);
Spread Operator ... 將陣列元素展開,相當於:
showPerson(...person1) ≡ showPerson("Keith", "Fung", "Firefighter")showPerson(...person2) ≡ showPerson("Marvin", "Chan", "Highschool student", "Pet Owner")